<template>
    <MainLayout :title="pageTitle" :breadcrumbItems="breadcrumbItems">
        <template #sidebar>
            <SideNav :items="navConfig" :active="currentNav.type" @select="handleSelect" />
        </template>

        <template #content>
            <div v-if="pending" class="loading">数据加载中...</div>
            <template v-else>
                <template v-if="academicItems.length">
                    <ContentList :items="academicItems" prevtype="academic" :type="currentNav.type" />
                    <Pagination :current-page="currentPage" :total-pages="totalPages"
                        :base-url="localePath(`/academic/${currentNav.type}`)" />
                </template>
                <div v-else class="empty">暂无数据</div>
            </template>
        </template>
    </MainLayout>
</template>

<script setup>
import MainLayout from '@/components/ListPage.vue'
import SideNav from '@/components/list/SideNav.vue'
import ContentList from '@/components/academic/list.vue'
import Pagination from '@/components/list/Pagination.vue'

const route = useRoute()
const router = useRouter()
const { $fetchGov } = useNuxtApp()
import { formatDate } from '@/utils/date'

const localePath = useLocalePath()
//当前频道id
const currentChannelId = ref('')
const currentPage = ref(1)
const totalPages = ref(20)
const academicItems = ref([])
const pending = ref(true)

// 获取频道列表数据
const { data: academic } = await useAsyncData(
  `academic-channel-${new Date().getTime()}`,
  () => $fetchGov('/app/api/channel/alias/academic', {
    method: 'GET',
    params: { isArticle: false, isTree: false },
    _t: Date.now()
  })
)

// 导航配置
const navConfig = computed(() => {
  return (academic.value?.data?.children || []).map(item => ({
    // 添加错误处理
    type: item.routerPath,
    title: item.name,
    id: item.id,
    path: `/academic/${item.routerPath}`
  }))
})

const debounce = (fn, delay) => {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
};

// 第二步：初始化防抖控制器
let abortController = null
const debouncedFetch = debounce(async () => {
  pending.value = true;
  try {
    // 取消未完成的请求
    if (abortController) abortController.abort()
    abortController = new AbortController()

    // 执行数据请求
    const { data: responseData } = await $fetchGov('/app/api/article/page', {
      signal: abortController.signal,
      params: {
        channelId: currentChannelId.value,
        page: currentPage.value,
        pageSize: 5,
        _t: Date.now()
      }
    })

    // 安全处理数据
    academicItems.value = Array.isArray(responseData?.content)
      ? responseData?.content.map(formatItem)
      : []
    totalPages.value = Number(responseData?.totalPages) || 0
  } catch (err) {
    if (err.name === 'AbortError') {
      console.log('请求被取消')
    } else {
      console.error('请求失败:', err)
      academicItems.value = []
      totalPages.value = 0
    }
  }finally {
    pending.value = false;
  }
}, 300)

// 第三步：路由参数初始化
const initParams = () => {
  const routeType = route.params.type
  const targetNav = navConfig.value.find(nav => nav.type === routeType)

  currentChannelId.value = targetNav?.id || ''
  currentPage.value = Number(route.query.page) || 1
}

// 第四步：统一监听变化
watch(
  [() => route.params.type, () => route.query.page],
  () => {
    // 添加防抖控制
    if (!navConfig.value.length) return
    initParams()
    debouncedFetch()
  },
  { immediate: true }
)

// 辅助函数
const formatItem = item => ({
  id: item.id,
  title: item.title.trim(),
  image: item.image,
  tags: item.tags,
  description: item.description,
  date: formatDate(item.publishDate)
})

const pageTitle = computed(() => {
  return academic.value?.data?.name || '学术交流'
})

// 获取当前导航状态
const currentNav = computed(() =>
  navConfig.value.find(nav => nav.type === route.params.type) || { title: '', type: '' }
)


// 面包屑导航
const breadcrumbItems = computed(() => [
    { title: '首页', path: '/' },
    { title: '学术交流', path: '/academic' },
    { title: currentNav.value.title }
])

// 切换导航处理
const handleSelect = async (item) => {
  router.push(
    localePath({
      path: `/academic/${item.type}`
    })
  )
}
</script>

<style scoped>
/* 添加样式 */
</style>